package com.shujia.junit;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.sql.*;

public class Demo3Jdbc {

    Connection connection;

    @Before
    public void init() {
        //创建jdbc连接

        //1、加载驱动
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

        //2、创建连接

        try {
            connection = DriverManager.getConnection("jdbc:mysql://node1:3306/con", "root", "123456");
        } catch (SQLException e) {
            e.printStackTrace();
        }


    }


    @Test
    public void test() {
        System.out.println(connection);

    }


    @Test
    public void select() {
        try {
            Statement stat = connection.createStatement();

            ResultSet resultSet = stat.executeQuery("select * from user");

            while (resultSet.next()) {
                String username = resultSet.getString("username");
                int age = resultSet.getInt("age");

                System.out.println(username + "\t" + age);
            }

        } catch (SQLException e) {
            e.printStackTrace();
        }

    }


    @After
    public void close() {

        //关闭连接
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }


}
